package com.ksxy.afingerprint.ui.dialog

import android.app.Dialog
import android.hardware.fingerprint.FingerprintManager
import android.os.Build
import android.os.Bundle
import android.os.CancellationSignal
import android.os.Handler
import android.support.v4.app.DialogFragment
import android.support.v7.app.AlertDialog
import android.util.Log
import android.view.LayoutInflater
import android.widget.ImageView
import android.widget.TextView
import com.ksxy.afingerprint.R
import com.ksxy.afingerprint.core.FingerPrintAuthHelper
import com.ksxy.afingerprint.utils.showShortToast
import javax.crypto.Cipher

/**
 *  author : chenyinying
 *  e-mail : me@korion.cn
 *  time   : 2018/07/07
 *  desc   :
 *  version: 1.0
 */
class FingerPrintAuthRequestDialog(): DialogFragment(){

    companion object {
        val TAG = FingerPrintAuthRequestDialog::class.java.name
    }

    private var mCipher: Cipher? = null
    private var img_fingerprint: ImageView? = null
    private var tv_tip: TextView? = null
    private var mCallBack: CallBack? = null

    public fun setCipher(cipher: Cipher): FingerPrintAuthRequestDialog{
        mCipher = cipher
        return this
    }

    public fun setAuthCallBack(callBack: CallBack): FingerPrintAuthRequestDialog{
        mCallBack = callBack
        return this
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        super.onCreateDialog(savedInstanceState)
        val view = LayoutInflater.from(context!!).inflate(R.layout.dialog_fingerprint_auth_request, null)
        img_fingerprint = view.findViewById(R.id.img_fingerprint)
        tv_tip = view.findViewById(R.id.tv_tip)
        return AlertDialog.Builder(context!!)
                .setTitle(context!!.getString(R.string.need_fingerprint_auth))
                .setView(view)
                .create()
    }

    private var cancelObject: CancellationSignal? = null

    override fun onStart() {
        super.onStart()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            cancelObject = FingerPrintAuthHelper.from(context!!).authenticate(mCipher!!, object:
                    FingerprintManager.AuthenticationCallback(){

                var tryCount = 0
                override fun onAuthenticationError(errorCode: Int, errString: CharSequence?) {
                    //Log.d(TAG, "errorCode: ${errorCode} errString: ${errString}")
                    if(errorCode == 7){
                        tv_tip?.text = context!!.getString(R.string.wait_to_retry)
                    }
                    mCallBack?.onAuthenticationError()

                }

                override fun onAuthenticationSucceeded(result: FingerprintManager.AuthenticationResult?) {
                    img_fingerprint?.animate()?.duration = 500
                    img_fingerprint?.setImageResource(R.drawable.ic_fingerprint_passed)
                    tv_tip?.text = context!!.getString(R.string.auth_passed)
                    mCallBack?.onAuthenticationSucceeded(result)
                    delayRun(Runnable { dismiss() })
                }

                override fun onAuthenticationHelp(helpCode: Int, helpString: CharSequence?) {

                }

                override fun onAuthenticationFailed() {
                    tryCount++
                    //Log.d(TAG, "第${tryCount}次尝试失败")
                    tv_tip?.text = context!!.getString(R.string.try_again)
                }
            }, null)
            context?.showShortToast(context!!.getString(R.string.put_finger))
        }
    }

    override fun onStop() {
        super.onStop()
        cancelObject?.cancel()
    }

    private fun delayRun(r: Runnable){
        Handler().postDelayed(r, 800)
    }

    interface CallBack{
        fun onAuthenticationSucceeded(result: FingerprintManager.AuthenticationResult?)
        fun onAuthenticationError()
    }
}